from google.appengine.ext import webapp                                        
from google.appengine.ext.webapp.util import run_wsgi_app                      
import logging                                                                 
     
from StringIO import StringIO                                                  
import traceback
import xmlrpclib
from xmlrpcserver import XmlRpcServer
from google.appengine.ext import db
import datetime
from xmw import tianya
import xmw
from xmw import error
class TheadMgr:
    def reg_url(self,url):
        thread=tianya.TianyaThread.query_thread_by_url(url)
        if thread is not None:
            if thread.status == xmw.Thread_Status.RUN:
                return (thread.thread_id,error.OK("url's nest thread being traced!").to_dict())
            if thread.status == xmw.Thread_Status.BAD:
                return (None,error.URL_BAD("bad url:%s"%url).to_dict())
                #duplicated url
            return (None,error.URL_ACCEPTED("already accepted!just waitting.url:%s"%url).to_dict())
        else:
            thread=tianya.TianyaThread()
            thread.created = xmw.get_cn_now_time()
            thread.latest_post_date=thread.created
            lst=[url]
            thread.lst_page_url=lst
            thread.put()
            return (None,error.URL_ACCEPTED(url).to_dict())
        
    def query_thread_id_by_url(self,url):
        thread=tianya.TianyaThread.query_thread_by_url(url)
        if thread is None:
            return None
        
        if thread.thread_id == "NA":
            return None
        
        return thread.thread_id
    
    def echo(self,msg):
        return msg
            
            
class XMLRpcHandler(webapp.RequestHandler):                                    
    rpcserver = None
                                
    def __init__(self):         
        self.rpcserver = XmlRpcServer()                                        
        thead_mgr = TheadMgr()                                                    
        self.rpcserver.register_class('thead_mgr',xmw.XmlRpcWrapper(thead_mgr))                               
                                                                               
    def post(self):
        request = StringIO(self.request.body)
        request.seek(0)                                                        
        response = StringIO()                                                  
        try:
            self.rpcserver.execute(request, response, None)                    
        except Exception, e:                                                   
            logging.error('Error executing: '+str(e))                          
            for line in traceback.format_exc().split('\n'):                    
                logging.error(line)
        finally:
            response.seek(0)  
                                                                               
        rstr = response.read()                                                 
        self.response.headers['Content-type'] = 'text/xml'                     
        self.response.headers['Content-length'] = "%d"%len(rstr)               
        self.response.out.write(rstr)
                                                                               
application = webapp.WSGIApplication(                                          
                                     [('/xmlrpc/thread_mgr', XMLRpcHandler)],
                                     debug=True)                               
def main():
  run_wsgi_app(application)                                                    
        
if __name__ == "__main__":
    main()